package geekbang.single;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xuyanqing
 * @description ✨双重检测，既支持延迟加载、又支持高并发的单例实现方式，也就是双重检测实现方式
 * @date 2025-10-11 15:35
 * @creed where there is a will,there is a way. yx
 */

public class IdGeneratorDoubleCheck {

    private static IdGeneratorDoubleCheck instance;

    private IdGeneratorDoubleCheck() {
    }

    // 双重检测实现方式，只要 instance 被创建之后，再调用 getInstance() 函数都不会进入到加锁逻辑中
    public static IdGeneratorDoubleCheck getInstance() {
        if (instance == null) {
            synchronized (IdGeneratorDoubleCheck.class) {
                if (instance == null) {
                    instance = new IdGeneratorDoubleCheck();
                }
            }
        }
        return instance;
    }

    // 懒汉式（性能问题，频繁加锁、释放锁）
    /*public static synchronized IdGeneratorDoubleCheck getInstance() {
        if (instance == null) {
            instance = new IdGeneratorDoubleCheck();
        }
        return instance;
    }*/

    private AtomicInteger id = new AtomicInteger(0);

    public long getId() {
        return id.incrementAndGet();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(IdGeneratorDoubleCheck.getInstance().getId())).start();
        }
    }
}
